package com.bfly.mall.shop.service.impl;

import com.bfly.core.base.service.BaseServiceImpl;
import com.bfly.mall.shop.dao.ShopMapper;
import com.bfly.mall.shop.dao.ShopPicMapper;
import com.bfly.mall.shop.entity.Shop;
import com.bfly.mall.shop.dto.ShopFormDTO;
import com.bfly.mall.shop.entity.ShopPic;
import com.bfly.mall.shop.service.IShopService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author 长沙商脉科技有限公司
 * @date 2020/11/27 19:37
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS)
public class ShopServiceImpl extends BaseServiceImpl<Shop, Integer> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private ShopPicMapper shopPicMapper;

    @Override
    public Shop getShop() {
        return shopMapper.getShop();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void merge(ShopFormDTO formDTO) {
        Shop shop = get(formDTO.getId());
        if (shop == null) {
            // 新增门店信息
            shop = new Shop();
            BeanUtils.copyProperties(formDTO, shop);
            shop.setCreateDate(new Date());
            super.save(shop);
        } else {
            // 修改门店信息
            shop.setName(formDTO.getName());
            shop.setAddress(formDTO.getAddress());
            shop.setLongitude(formDTO.getLongitude());
            shop.setLatitude(formDTO.getLatitude());
            shop.setLogo(formDTO.getLogo());
            shop.setPhone(formDTO.getPhone());
            shop.setRemark(formDTO.getRemark());
            shop.setStartTime(formDTO.getStartTime());
            shop.setEndTime(formDTO.getEndTime());
            shop.setUpdateDate(new Date());
            super.edit(shop);
        }

        // 保存门店图片先清空再保存
        List<ShopPic> pics = formDTO.getPics();
        shopPicMapper.clearShopPic(shop.getId());
        if(pics!=null) {
            final int shopId = shop.getId();
            pics.forEach(shopPic -> {
                shopPic.setShopId(shopId);
                shopPicMapper.insert(shopPic);
            });
        }
    }
}
